package com.briup.prs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;

/**
 * @author adam
 * @date 2022/2/8
 * 得到每个商品 的用户喜好矩阵
 */
public class Step2 extends Configured implements Tool {
    public  static  class S2Mapper extends Mapper<LongWritable, Text,Text,Text> {

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
//            [0]: 用户ID：商品id   [1]:偏好值
            String[] data = value.toString().split("[\t]");
//            userAndShop[0]:userAndShop     userAndShop[1]:商品id
            String[] userAndShop = data[0].split("[:]");
            Text oKey = new Text(userAndShop[1]);
            Text oValue = new Text(userAndShop[0] + "-" + data[1]);
//            key:商品id   value:用户id-偏好值
            context.write(oKey,oValue);
        }
    }
    public static  class  S2Reducer extends Reducer<Text,Text,Text,Text>{
        @Override
        protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
            String oValue="";
            for (Text value : values) {
                oValue+=value.toString()+",";
            }
//            去除末尾的标点符号
            oValue=oValue.substring(0,oValue.length()-1);
            context.write(key,new Text(oValue));
        }
    }
    @Override
    public int run(String[] strings) throws Exception {
        Configuration conf = getConf();
        String in = conf.get("in");
        String out = conf.get("out");
        Job job = Job.getInstance(conf, "step2");
        job.setJarByClass(Step2.class);
        job.setMapperClass(S2Mapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(Text.class);

        job.setReducerClass(S2Reducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(Text.class);
        job.setInputFormatClass(TextInputFormat.class);
        TextInputFormat .addInputPath(job,new Path(in));
        job.setOutputFormatClass(TextOutputFormat.class);
        TextOutputFormat.setOutputPath(job,new Path(out));
        job.waitForCompletion(true);
        return 0;
    }

    public static void main(String[] args) throws Exception {
        ToolRunner.run(new Step2(),args);
    }
}
